package com.zhiletu.collect.util;

import java.io.File;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.zhiletu.collect.Collecter;

/**
 *
 * @Title: js脚本执行Java引擎
 * @Package com.zhiletu.collect.util
 * @Description: 在Java后端执行js脚本的前后端打通工具
 * @author zhiletu.com
 * @date 2021年3月11日
 * @version V1.0
 */
public class ScriptingAPI {

	public static void main(String[] args) throws Exception {
//        ScriptEngineManager manager = new ScriptEngineManager();
//        ScriptEngine engine = manager.getEngineByName("JavaScript");
//        testScriptVariables(engine);//演示如何暴露Java对象为脚本语言的全局变量
//         testInvokeScriptMethod(engine);//演示如何在Java中调用脚本语言的方法
//         testScriptInterface(engine);//演示脚本语言如何实现Java的接口
//         testUsingJDKClasses(engine);//演示脚本语言如何使用JDK平台下的类 
		// http://dict.baidu.com/s?wd=%E5%A4%A7%E5%AE%B6&ptype=word 中文词组
		// http://dict.baidu.com/s?wd=%E6%9C%8B&ptype=word 中文单字
		// http://dict.baidu.com/s?wd=%E7%8B%97%E8%9B%8B&ptype=word 未找到
		// http://dict.baidu.com/s?wd=fuck   英文单词
		// http://dict.baidu.com/s?wd=how are you 英文词组
		StringBuffer html = Collecter.readStream("http://wenxue.yjbys.com/shige/13384.html", true, "gbk");
    	 
    	/*
    	script_Pattern="<script[^>]*?>[\s\S]*?<\/script>"     '匹配js标签
	    style_Pattern="<style[^>]*?>[\s\S]*?<\/style>"      '匹配style标签
	    <>_Pattern="<(.|\n)+?>"   '匹配html标签
	    <p>((\w|\W)*?)</p> 匹配p标签
	    */

		/*去掉所有的html标记(除了p标签)*/
		String delHtmlTag = "function delHtmlTag(str){str = str.replace(/<script[^>]*?>[\\s\\S]*?<\\/script>/g,\"\"); str = str.replace(/<style[^>]*?>[\\s\\S]*?<\\/style>/g,\"\"); return str.replace(/<(?!\\/?[pP])[^>]+>/g,\"\");}";
//    	
		String content = ScriptingAPI.invokeScript(delHtmlTag, "delHtmlTag", new Object[] { html.toString() });
		//String content = DictTool.queryDict("诡谲");
		System.out.println(content);

//    	String onload = "window.onload=function(str){var d=document.createElement('body');d.innerHTML=str;return d.innerText;}";
//    	
//    	content = ScriptingAPI.invokeScript(onload, "window.onload", content);
//    	
//    	System.out.println(content);
	}

	public static void testScriptVariables(ScriptEngine engine) throws ScriptException {
		File file = new File("test.txt");
		engine.put("f", file);
		engine.eval("println('Total Space:'+f.getTotalSpace())");
	}

	public static void testInvokeScriptMethod(ScriptEngine engine) throws Exception {
		String script = "function hello(name) { return 'Hello,' + name;}";
		engine.eval(script);
		Invocable inv = (Invocable) engine;
		String res = (String) inv.invokeFunction("hello", "Scripting");
		System.out.println("res:" + res);
	}

	public static void testScriptInterface(ScriptEngine engine) throws ScriptException {
		String script = "var obj = new Object(); obj.run = function() { println('run method called'); }";
		engine.eval(script);
		Object obj = engine.get("obj");
		Invocable inv = (Invocable) engine;
		Runnable r = inv.getInterface(obj, Runnable.class);
		Thread th = new Thread(r);
		th.start();
	}

	public static void testUsingJDKClasses(ScriptEngine engine) throws Exception {
		//Packages是脚本语言里的一个全局变量,专用于访问JDK的package
		String js = "function doSwing(t){var f=new Packages.javax.swing.JFrame(t);f.setSize(400,300);f.setVisible(true);}";
		engine.eval(js);
		Invocable inv = (Invocable) engine;
		inv.invokeFunction("doSwing", "Scripting Swing");
	}


	/**
	 * 调用js脚本并传递java参数，返回执行结果
	 * @param script
	 * @param funName
	 * @param params
	 * @return
	 * @throws ScriptException
	 * @throws NoSuchMethodException
	 */
	public static String invokeScript(String script, String funName, Object... params) throws ScriptException, NoSuchMethodException {
		ScriptEngine engine = getJavaScriptEngine();
		engine.eval(script);
		Invocable inv = (Invocable) engine;
		String res = (String) inv.invokeFunction(funName, params);

		return res;
	}

	/**
	 * 获取js引擎
	 * @return
	 */
	protected static ScriptEngine getJavaScriptEngine() {
		ScriptEngineManager manager = new ScriptEngineManager();

		return manager.getEngineByName("JavaScript");
	}
}

